<?php
/**
 * 微信授权,只有微信浏览器授权，其他浏览器忽略
 * User: ran.ran
 * Date: 16/4/8
 * Time: 下午4:41
 * Describe:
 */
namespace wap\controllers;

use Yii;
use yii\web\Controller;
use services\models\MemberInfo;
use services\models\wap\WeiXinBindInfo;
use services\models\wap\WeiXinLoginLog;

class WeiXinOAtuhController extends Controller
{
    private  $appId;
    private  $appSecret;

    public $session;
    /**
     * 跨越外部登陆url地址
     * @var string
     */
    protected $login_url;
    
    /**
     *是否是微信浏览器，微信浏览器获取openid，并且openid有值，其他浏览器openid不存在，不作处理 
     * @var boolen
     */
    public $is_wechat = false;
    
    public function init()
    {
        //设置晒单登陆地址
        $this->login_url = Yii::$app->params['wx_login_url'];
        //微信appid
        $this->appId = Yii::$app->params['wxpay']['appid'];
        //微信appSecret
        $this->appSecret = Yii::$app->params['wxpay']['appsecret'];
        //微信浏览true
        $this->is_wechat = true;//$this->checkIsWeChatBrowser();禁止外部浏览器。以后自动判断
        //设置session
        $this->session =Yii::$app->session; 
        
        $this->index();
    }
	
    //入口
    public final  function index() 
    {
        $wap_uid =  $this->session->get(Yii::$app->params['wap_uid'],null);//会员登陆uid
        $wx_open_id = $this->session->get(Yii::$app->params['wx_open_id'], null); //openid
        //判断是否微信浏
        if($this->is_wechat) 
        {
            if(empty($wap_uid)) 
            {
                if(empty($wx_open_id)) 
                {
                    $wx_open_id = $this->GetOpenid(); //openid不存在授权
                    $wx_open_id = trim($wx_open_id);
                    //设置session openid
                    $this->session->set(Yii::$app->params['wx_open_id'],$wx_open_id);
                }
                
                //通过openid自动登录微信
                if(!empty($wx_open_id)) {
                    $wx_bind_info =  WeiXinBindInfo::findOne(['openid'=>$wx_open_id]);
                    if(!empty($wx_bind_info) && !empty($wx_bind_info->member_no))
                    {
                        $member_info =  MemberInfo::getMemberInfo(['member_no'=>$wx_bind_info->member_no]);
                         
                        $this->session->set(Yii::$app->params['wap_uid'],$member_info->member_no);
                        $this->session->set(Yii::$app->params['wap_name'],$member_info ->username);
                        $this->session->set(Yii::$app->params['wap_bestry_uid'],$member_info->getMember_uid());
                         
                        //插入绑定记录wap_login_log
                        $wapLog = new WeiXinLoginLog();
                        $wapLog->member_no = $wx_bind_info->member_no;
                        $wapLog->addtime = time();
                        $wapLog->ip = ip2long($_SERVER['REMOTE_ADDR']);
                        $wapLog->type = 1;
                        $wapLog->save(true);
                
                    }
                }
            }

        }
        
    }
    
	/**
	 * 获取openid
	 * @return mixed
	 */
	public function GetOpenid()
	{
		//通过code获得openid
		$temp_code = Yii::$app->request->get('code',null);
		if (!$temp_code){
			//触发微信返回code码
			$baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);//('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
			$url = $this->__CreateOauthUrlForCode($baseUrl);
			Header("Location: $url");
			exit();
		} else {
			//获取code码，以获取openid
		    $code = Yii::$app->request->get('code');
			$openid = $this->getOpenidFromMp($code);
			return $openid;
		}
	}
	
	/**
	 * 创建授权url
	 * @param string $redirectUrl 回调地址
	 * @return string
	 */
	private function __CreateOauthUrlForCode($redirectUrl)
	{
		$urlObj["appid"] = $this->appId;
		$urlObj["redirect_uri"] = "$redirectUrl";
		$urlObj["response_type"] = "code";
		$urlObj["scope"] = "snsapi_base";
		$urlObj["state"] = "STATE"."#wechat_redirect";
		$bizString = $this->ToUrlParams($urlObj);
		return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
	}
	
	/**
	 * 拼接&带code参数
	 * @param string $code code
	 */
	private function __CreateOauthUrlForOpenid($code)
	{
		$urlObj["appid"] = $this->appId;
		$urlObj["secret"] = $this->appSecret;
		$urlObj["code"] = $code;
		$urlObj["grant_type"] = "authorization_code";
		$bizString = $this->ToUrlParams($urlObj);
		return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
	}
	
	
	/**
	 * 通过code获取openid
	 * @param string $code
	 */
	public function GetOpenidFromMp($code)
	{
		$url = $this->__CreateOauthUrlForOpenid($code);
		//初始化curl
		
		$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
	
		//取出openid
		$data = json_decode($output,true);
		$openid = $data['openid'];
		return $openid;
	}
	
	/**
	 * 将数组拼接&字符串
	 * @param unknown $urlObj
	 */
	private function ToUrlParams($urlObj)
	{
		$buff = "";
		foreach ($urlObj as $k => $v)
		{
			if($k != "sign"){
				$buff .= $k . "=" . $v . "&";
			}
		}
		
		$buff = trim($buff, "&");
		return $buff;
	}
	
    /**
     * 检查是否是微信浏览器
     */
    private function checkIsWeChatBrowser(){
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
        }
        return false;
    }
}
